<script setup lang="ts">
import { reactive, ref } from 'vue'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { ElMessage } from 'element-plus';
import 'element-plus/theme-chalk/el-loading.css';
import 'element-plus/theme-chalk/el-message.css';
import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';
import type { UploadInstance } from 'element-plus'
import { onMounted, onUpdated } from "vue";
import { preinfoApi, seachinfoApi, changeinfoApi, changeSinfoApi } from '../apis/appinfoApi'
//接口
interface Info {
    idCard: string
    packageName: string
    preStatus: number | string
    preTime: string
    preinfoId: number
    subOrganName: string
    prepeopleName: string
    prepeoplePhone: string
    prepeopleGender: number | string
}

//声明变量
const size = ref<'' | 'large' | 'small'>('')
const value1 = ref('')
const dialogVisible = ref(false)
const shortcuts = reactive([
    {
        text: '上一周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: '上个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        },
    },
    {
        text: '前三个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
        },
    },
])
const formAppInfo = reactive({
    query: null,
    preTime: null,
    preStatus: null,
    startTime: null,
    endTime: null,
    page: 1,
    size: 5
});
const AppTableData = reactive<Info[]>([])
const locale = zhCn;//分页语言设置
const currentPage4 = ref(1)
const pageSize4 = ref(50)
const pageSize = ref(5)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const dialogTableVisible = ref(false)
const centerDialogVisible = ref(false)
const radio1 = ref(3)
const preinfoId = ref(null)
let stateArr = [];
let selectedDate = ref(null)

//渲染数据
const render = async () => {
    AppTableData.length = 0
    const { data }: { [propsName: string]: any } = await preinfoApi({ page: currentPage4.value, size: pageSize4.value })
    if (data.code == 0) {
        AppTableData.push(...data.data)
        //修改时间戳
        AppTableData.forEach((v) => {
            let preTime = v.preTime.substring(0, 10)
            v.preTime = preTime
            //判断体检状态
            switch (v.preStatus) {
                case 1:
                    v.preStatus = '待支付';
                    break;
                case 2:
                    v.preStatus = '待体检';
                    break;
                case 3:
                    v.preStatus = '已完成';
                    break;
                case 4:
                    v.preStatus = '已过期';
                    break;
                case 5:
                    v.preStatus = '退款中';
                    break;
                case 6:
                    v.preStatus = '已退款';
                    break;
            }
            //判断性别
            switch (v.prepeopleGender) {
                case 1:
                    v.prepeopleGender = '男';
                    break;
                case 2:
                    v.prepeopleGender = '女';
                    break;
            }
        })
    }
}
render()
// const pageDate = computed(() => {
//     return AppTableData.slice(currentPage4.value - 1,currentPage4.value * pageSize4.value)
// })
//声明方法
const dateChange = (row: Info) => {
    dialogTableVisible.value = true
    preinfoId.value = row.preinfoId
    console.log('点击行数据:', row);

}
const stateChange = async (row: Info) => {
    dialogVisible.value = true
    preinfoId.value = row.preinfoId
    console.log('点击行数据:', row);
}
const stateSure = async () => {
    if (stateArr.length != 0) {//批量修改状态
        const { data }: { [propsName: string]: any } = await changeSinfoApi({ preinfoIds: stateArr, status: radio1.value })
        if (data.code == 0) {
            dialogVisible.value = false
            render()
            ElMessage({
                message: '修改成功',
                type: 'success',
            })
            stateArr.length = 0
        } else {
            ElMessage({
                type: 'error',
                message: data.msg
            })
        }
    } else if (stateArr.length == 0) {
        const { data }: { [propsName: string]: any } = await changeinfoApi({ preinfoId: preinfoId.value, status: radio1.value })
        if (data.code == 0) {
            dialogVisible.value = false
            render()
            ElMessage({
                message: '修改成功',
                type: 'success',
            })
        }
        else {
            ElMessage({
                type: 'error',
                message: data.msg
            })
        }
    }
}
const dateSure = async () => {
    console.log(formDate(selectedDate.value));
    const { data }: { [propsName: string]: any } = await changeinfoApi({ preinfoId: preinfoId.value, preTime: formDate(selectedDate.value) })
    if (data.code == 0) {
        ElMessage({
            message: '修改时间成功',
            type: 'success',
        })
        dialogTableVisible.value = false
        render()
    } else {
        ElMessage({
            type: 'error',
            message: data.msg
        })
    }
}
const multipleSelection = ref<Info[]>([])
const handleSelectionChange = (val: Info[]) => {
    stateArr.length = 0;
    multipleSelection.value = val
    const normalArray = Object.values(multipleSelection.value);
    normalArray.forEach(v => {
        stateArr.push(v.preinfoId)
    });
}
//转换时间格式
const formDate = (dateString) => {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).slice(-2);
    const day = ('0' + date.getDate()).slice(-2);

    return `${year}-${month}-${day}`;
}
const onSubmit = async () => {
    if (formAppInfo.preTime != null) {
        let normalArray = Object.values(formAppInfo.preTime);
        formAppInfo.startTime = formDate(normalArray[0]);
        formAppInfo.endTime = formDate(normalArray[1]);
    }
    const { data }: { [propsName: string]: any } = await seachinfoApi({ query: formAppInfo.query, preStatus: formAppInfo.preStatus, startTime: formAppInfo.startTime, endTime: formAppInfo.endTime, page: 1, size: 5 })
    if (data.code == 0) {
        ElMessage({
            message: '查询成功',
            type: 'success',
        })
        AppTableData.length = 0;
        AppTableData.push(...data.data)
        //修改时间戳
        AppTableData.forEach((v) => {
            let preTime = v.preTime.substring(0, 10)
            v.preTime = preTime
            //判断体检状态
            switch (v.preStatus) {
                case 1:
                    v.preStatus = '待支付';
                    break;
                case 2:
                    v.preStatus = '待体检';
                    break;
                case 3:
                    v.preStatus = '已完成';
                    break;
                case 4:
                    v.preStatus = '已过期';
                    break;
                case 5:
                    v.preStatus = '已取消';
                    break;
                case 6:
                    v.preStatus = '已退款';
                    break;
                    case 7:
                    v.preStatus = '已失效';
                    break;
            }
            //判断性别
            switch (v.prepeopleGender) {
                case 1:
                    v.prepeopleGender = '男';
                    break;
                case 2:
                    v.prepeopleGender = '女';
                    break;
            }
        })
    } else {
        ElMessage({
            type: 'error',
            message: data.msg
        })
    }
}
const handleSizeChange = (val: number) => {
    pageSize4.value = val;
    console.log(`每页${val} 条`)
}
const handleCurrentChange = (val: number) => {
    currentPage4.value = val
    console.log(`当前页: ${val}`)
}
// Excel表格模板下载
const downloadExcel = () => {
    const data = [{ '姓名': '', '性别': '', '手机': '', '身份证号': '', '体检内容': '', '体检机构': '', '体检日期': '', '订单号': '', '体检状态': '' }]
    const sheet = XLSX.utils.json_to_sheet(data);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, sheet, "Sheet1");

    const excelBuffer = XLSX.write(workbook, { bookType: "xlsx", type: "array" });

    const blob = new Blob([excelBuffer], { type: "application/octet-stream" });
    saveAs(blob, "预约信息模板.xlsx");
}
// 文件上传
const toFile = () => {
    submitUpload()
}
const uploadRef = ref<UploadInstance>()

const submitUpload = () => {
    uploadRef.value!.submit()
}
const AppReast = () => {
    //重置
    render()
}
// onUpdated(() => {
//     // console.log(pageDate);
//     // console.log();
//     render()

// });
</script>
<template>
    <zlj-header msg="预约信息管理"></zlj-header>
    <el-container style="background-color: #f5f7fa;padding:0 ;">
        <el-main style="margin:1rem 1rem 0 1rem;background-color: rgb(255, 255, 255);">
            <div class="pick">
                <h4>数据筛选</h4>
                <div class="pick-form">
                    <div>
                        <el-form :inline="true" :model="formAppInfo" class="demo-form-inline">
                            <el-form-item label="输入查询：">
                                <el-input v-model="formAppInfo.query" placeholder="姓名/手机号/身份证号/订单号" clearable
                                    style="width: 14rem;" />
                            </el-form-item>
                            <el-form-item label="体检状态：">
                                <el-select v-model="formAppInfo.preStatus" placeholder="全部" clearable class="state">
                                    <el-option label="全部" :value="0" />
                                    <el-option label="待支付" :value="1" />
                                    <el-option label="待体检" :value="2" />
                                    <el-option label="已完成" :value="3" />
                                    <el-option label="已过期" :value="4" />
                                    <el-option label="已取消" :value="5" />
                                    <el-option label="已退款" :value="6" />
                                    <el-option label="已失效" :value="7" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="体检日期：" class="zlj-date">
                                <div class="demo-date-picker">
                                    <div class="block">
                                        <el-date-picker v-model="formAppInfo.preTime" type="daterange" range-separator="至"
                                            start-placeholder="开始日期" end-placeholder="结束日期" :size="size"
                                            :shortcuts="shortcuts" />
                                    </div>
                                </div>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="onSubmit">查询</el-button>
                                <el-button @click="AppReast">重置</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div>
                    </div>
                </div>
            </div>
            <div class="zlj-btn2">
                <el-button @click="stateChange">修改状态</el-button>
                <el-upload style="display: inline-block;margin-right: 10px;" ref="uploadRef" class="upload-demo"
                    action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" :auto-upload="false">
                    <template #trigger>
                        <el-button style="margin-left: 10px;" @click="toFile">导入</el-button></template></el-upload>
                <el-button @click="downloadExcel">下载Excel模板</el-button>
            </div>
            <!-- 表格 -->
            <div class="zlj-table">
                <el-table ref="multipleTableRef"
                    :data="AppTableData.slice((currentPage4 - 1) * pageSize, currentPage4 * pageSize)" border stripe
                    style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" style="background-color: #eee;" />
                    <el-table-column property="prepeopleName" label="姓名">
                    </el-table-column>
                    <el-table-column property="prepeopleGender" label="性别" />
                    <el-table-column property="prepeoplePhone" label="手机" />
                    <el-table-column property="packageName" label="内容" />
                    <el-table-column property="idCard" label="身份证号" />
                    <el-table-column property="subOrganName" label="体检机构" />
                    <el-table-column property="preTime" label="体检日期" />
                    <el-table-column property="preinfoId" label="订单号" />
                    <el-table-column property="preStatus" label="体检状态" />
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button link type="success" size="small" style="padding: 0;"
                                @click="dateChange(scope.row)">修改时间</el-button>
                            <el-button link type="success" size="small" style="padding: 0;"
                                @click="stateChange(scope.row)">修改状态</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页 -->
            <div class="demo-pagination-block">
                <el-config-provider :locale="locale">
                    <el-pagination v-model:current-page="currentPage4" :page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
                        :default-page-size="5" :small="small" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next, jumper" :total="AppTableData.length"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </el-config-provider>
            </div>
        </el-main>
    </el-container>
    <!-- 修改状态弹框 -->
    <el-dialog v-model="dialogVisible" title="修改状态" width="30%">
        <span style="margin: 8px;">目标状态:</span>
        <el-radio-group v-model="radio1" class="ml-4">
            <el-radio :label="3" size="large">已完成</el-radio>
            <el-radio :label="4" size="large">已过期</el-radio>
        </el-radio-group>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="stateSure">提交</el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 修改时间弹框 -->
    <el-dialog v-model="dialogTableVisible" title="修改时间">
        <el-calendar v-model="selectedDate">
            <template #dateCell="{ data }">
                <p :class="data.isSelected ? 'is-selected' : ''">
                    {{ data.day.split('-').slice(1).join('-') }}
                    {{ data.isSelected ? '✔️' : '' }}
                </p>
            </template>
        </el-calendar>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button type="primary" @click="dateSure">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style scoped lang="less">
.zlj-btn2 {
    margin: 1rem;
}

.el-main {
    padding: 0;
    position: relative;

    .state {
        width: 8rem;
    }

    .demo-date-picker {
        display: flex;
        width: 100%;
        padding: 0;
        flex-wrap: wrap;
    }

    .demo-date-picker .block {
        text-align: center;
        border-right: solid 1px var(--el-border-color);
        flex: 1;
    }

    .demo-date-picker .block:last-child {
        border-right: none;
    }

    .demo-date-picker .demonstration {
        display: block;
        color: var(--el-text-color-secondary);
        font-size: 14px;
        margin-bottom: 20px;
    }
}

.pick {
    border: 1px solid #ccc;
    margin: 0 1rem 0 1rem;

    .el-form--inline .el-form-item {
        margin-right: 10px;
        margin-left: 10px;
    }

    .el-form-item__label {
        padding: 0;
    }

    h4 {
        padding-left: 10px;
        font-size: 18px;
        margin: 8px 0;
    }
}

.is-selected {
    color: #1989fa;
}
</style>
<style lang="less">
.el-table .cell {
    padding: 0;
}

.cell {
    text-align: center;

    .el-checkbox {
        margin-left: 1.2rem;
    }
}

.demo-pagination-block {
    //分页样式
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin: 1rem;

    .el-pager li:hover {
        color: rgb(26, 188, 156);
    }

    li.is-active {
        color: rgb(26, 188, 156)
    }
}

.el-date-editor .el-range-input {
    padding: 0;
}

.el-input_wrapper {
    width: 5rem;
}

.el-dialog__header {
    background-color: rgba(242, 242, 242, 1);
    margin: 0;
    line-height: 30px;
}
</style>